<template>
	<view class="content bg-white">
		<view class="text-bold text-xl margin-bottom-sm padding-lr-sm" v-if="params.title">
			{{ params.title }}
		</view>
		<view class="banner margin-bottom" auto-focus v-if="params.images.length > 0">
			<image class="banner-img" :src="params.image_url"></image>
			<view class="title-area">
				<text class="title-text">{{params.title}}</text>
			</view>
		</view>
		<view class="cu-list menu-avatar">
			<view class="cu-item sm">
				<view class="cu-avatar round" :style="'background-image:url(' + params.avatar + ');'">
				</view>
				<view class="content flex-sub">
					<view class="text-gray">{{ params.nickname }}</view>
				</view>
			</view>
		</view>
		<view class="padding bg-white">
			<rich-text :nodes="content"></rich-text>
		</view>
		
		<!-- 评论列表 -->
		<view class="bg-gray padding-top-sm">
			<view class="cu-bar bg-white">
				<view class="action text-bold">评论</view>
			</view>
			<app-article-comment v-for="(comment, index) in comments" :comment="comment" :key="index" v-on:replyComment="handleShowReplyModal"></app-article-comment>
		</view>
		
		<!-- 评论 -->
		<view class="action-bar-wrap bg-white">
			<view class="solid-top"></view>
			<view class="bg-gray bg-white flex align-center padding-sm">
				<view class="flex-sub margin-right-xl bg-gray round padding-lr padding-tb-xs">
					<input type="text" value="" v-model="replyContent" placeholder="说点什么" confirm-type="done" @confirm="handleComment()" />
				</view>
				<view>
					<text class="xl text-gray" :class="params.is_collect ? 'cuIcon-favorfill' : 'cuIcon-favor'" @click="handleFavorite"></text>
				</view>
			</view>
		</view>
		
		<view class="cu-modal show" v-if="showReplyModal">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">回复</view>
					<view class="action" @click="handleHideReplyModal">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="padding-lg">
					<textarea value="" v-model="replyContent" placeholder="请输入" class="text-left" />
				</view>
				<view class="cu-bar bg-white justify-end">
					<view class="action">
						<button class="cu-btn bg-gradual-blue-plus margin-left" @click="handleReply">发送</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import htmlParser from '../../common/html-parser';

	const FAIL_CONTENT = '<p>获取信息失败1</p>';

	function parseImgs(nodes) {
		nodes.forEach(node => {
			if (
				node.name === 'img' &&
				node.attrs &&
				node.attrs['data-img-size-val']
			) {
				const sizes = node.attrs['data-img-size-val'].split(',')
				const width = uni.upx2px(720 * 0.9)
				const height = parseInt(width * (sizes[1] / sizes[0]))
				node.attrs.style = `width:${width};height:${height};`
			}
			if (Array.isArray(node.children)) {
				parseImgs(node.children)
			}
		})
		return nodes
	}
	
	// 注册评论组件
	import appArticleComment from '../../components/app-article-comment';

	export default {
		components: {
			'app-article-comment': appArticleComment
		},
		data() {
			return {
				isCollect: false,
				showReplyModal: false,
				replyContent: '',
				replyId: 0,
				params: {},
				content: [],
				comments: null
			}
		},
		watch: {
			'params.is_collect'(n, o) {
				console.log(n, o)
			}
		},
		onShareAppMessage() {
			return {
				title: this.params.title,
				path: '/pages/detail/detail?query=' + JSON.stringify(this.params)
			}
		},
		onLoad(event) {
			// 目前在某些平台参数会被主动 decode，暂时这样处理。

			this.load(event.query);
		},
		methods: {
			handleCheckCollect() {
				let flag = uni.getStorageSync(`collect:${this.params.id}`)
				
				if (flag !== true && this.params.is_collect) {
					return true;
				} else {
					return false;
				}
			},
			load(e) {
				let p = decodeURIComponent(e);
				
				try {
					this.params = JSON.parse(p);
				} catch (error) {
					this.params = JSON.parse(p);
				}

				uni.setNavigationBarTitle({
					title: this.params.title
				});
				
				this.isCollect = this.params.is_collect;

				this.getDetail();
			},
			// 获取详情
			getDetail() {
				let content = FAIL_CONTENT;
				
				if (this.params.content) {
					content = this.params.content;
				}
				
				const nodes = htmlParser(content);
				
				// #ifdef APP-PLUS-NVUE
				parseImgs(nodes);
				// #endif
				
				this.content = nodes;
				
				this.handleGetComments();
			},
			// 简单处理网络请求
			async handleRequest(querys) {
				let hideLoading = false;
				let hideMsg = false;
				
				if (!hideLoading) {
					uni.showLoading({
						title: '加载中',
						mask: true
					})
				}
				
				return new Promise((resolve, reject) => {
					let url = 'https://jianxia.mazhoudao.com/api/';

					uni.request({
						url: url,
						data: {
							data: JSON.stringify(querys)
						},
						success: (res) => {
							if (!hideLoading) uni.hideLoading();
							if (res.statusCode !== 200) {
								let err = `[${res.statusCode}] 请求失败`;

								uni.showToast({
									title: err,
									icon: 'none'
								});

								reject(err)
							} else {
								resolve(res.data);
							}
						},
						fail: (err) => {
							if (!hideLoading) uni.hideLoading();
							uni.showToast({
								title: `[${res.statusCode}] 请求失败`,
								icon: 'none'
							});
							
							reject(err);
						}
					})
				})
			},
			// 异步获取评论及评论的回复
			async handleGetComments() {
				await this.handleRequest({
					cmd: 'LunTan_GetReplay',
					nID: this.params.id
				}).then(async res => {
					if (res.length > 0) {
						await Promise.all(res.map(async (item, index) => {
							if (item.nCommentNum > 0) {
								await this.handleRequest({
									cmd: 'LunTan_GetReplay',
									nID: item.nID
								}).then(r => {
									item.reply = r;
								});
							}
						})).then(() => {
							this.comments = res;
						});
						return;
					}
					this.comments = [];
				})
			},
			// 显示回复窗口
			handleShowReplyModal(e) {
				this.replyId = e.nID;
				this.showReplyModal = true;
			},
			// 关闭回复窗口
			handleHideReplyModal(e) {
				this.replyId = 0;
				this.replyContent = '';
				this.showReplyModal = false;
			},
			// 回复
			async handleReply() {
				if (this.replyId === 0 || this.replyContent == '') {
					uni.showToast({
						icon: 'error',
						title: '参数不正确',
					})
					return;
				}
				await this.handleRequest({
					cmd: 'LunTan_Replay',
					nUid: uni.getStorageSync('uid') || 0,
					nID: this.replyId,
					sContent: this.replyContent
				}).then(res => {
					if (res.responseCode === '100') {
						uni.showToast({
							title: '回复成功',
							success: () => {
								this.replyContent = '';
								this.handleHideReplyModal();
								this.getDetail();
								// TODO 局部刷新
							}
						});
					} else {
						uni.showToast({
							icon: 'error',
							title: '回复失败',
							success: () => {}
						});
					}
				})
			},
			// 评论
			async handleComment() {
				await this.handleRequest({
					cmd: 'LunTan_Replay',
					nUid: uni.getStorageSync('uid') || 0,
					sContent: this.replyContent,
					nID: this.params.id
				}).then(res => {
					if (res.responseCode === '100') {
						uni.showToast({
							title: '评论成功',
							success: () => {}
						});
						this.replyContent = '';
						this.handleGetComments();
					} else {
						uni.showToast({
							icon: 'error',
							title: '评论失败',
							success: () => {}
						});
					}
				})
			},
			// 收藏
			async handleFavorite() {
				let uid = uni.getStorageSync('uid') || 0;
				
				if (uid === 0) {
					uni.showModal({
						title: '提示',
						content: '请先登录',
						success(res) {
							if (res.confirm) {
								uni.switchTab({
									url: '/pages/me/index'
								})
							}
						}
					})
					return;
				}
				
				let cmd = this.params.is_collect ? 'LunTan_PraiseDelete' : 'LunTan_Praise';
				
				await this.handleRequest({
					cmd: cmd,
					nUid: uid,
					nID: this.params.id
				}).then(res => {
					let msg = res.messageList[0].message || '';

					if (res.responseCode === '100') {
						if (cmd === 'LunTan_Praise') {
							this.params.is_collect = true;
						} else {
							this.params.is_collect = false;
						}
						uni.showToast({
							title: msg || (params.is_collect ? '收藏取消成功' : '收藏成功'),
							success: () => {}
						});
					} else {
						uni.showToast({
							icon: 'error',
							title: msg || (isCollect ? '收藏取消失败' : '收藏失败'),
							success: () => {}
						});
					}
				})
			}
		}
	}
</script>

<style>
	/* #ifndef APP-PLUS */
	page {
		min-height: 100%;
		margin-bottom: 120rpx;
	}

	/* #endif */

	.banner {
		height: 180px;
		position: relative;
		background-color: #ccc;
		flex-direction: row;
		overflow: hidden;
	}

	.banner-img {
		flex: 1;
	}

	.title-area {
		position: absolute;
		left: 15px;
		right: 15px;
		bottom: 15px;
		z-index: 11;
	}

	.title-text {
		font-size: 16px;
		font-weight: 400;
		line-height: 20px;
		lines: 2;
		color: #ffffff;
		overflow: hidden;
	}

	.article-meta {
		padding: 10px 15px;
		flex-direction: row;
		align-items: center;
		justify-content: flex-start;
	}

	.article-meta-text {
		color: gray;
	}

	.article-text {
		font-size: 12px;
		line-height: 25px;
		margin: 0 10px;
	}

	.article-author {
		font-size: 15px;
	}

	.article-time {
		font-size: 15px;
	}

	.article-content {
		font-size: 15px;
		padding: 0 15px;
		margin-bottom: 15px;
		overflow: hidden;
	}

	/* #ifdef H5 */

	.article-content {
		line-height: 1.8;
	}

	.article-content img {
		max-width: 100%;
	}

	/* #endif */
	
	page {
		background-color: #ffffff;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
	}
	
	.cu-list.menu-avatar > .cu-item.sm {
		height: 80rpx;
	}
	
	.cu-list.menu-avatar > .cu-item:after {
		border-bottom: none;
	}
	
	.cu-list.menu-avatar > .cu-item.sm .content {
		left: 110rpx;
	}
	
	.action-bar-wrap {
		position: fixed;
		left: 0;
		right: 0;
		z-index: 1;
		bottom: 0;
		padding-bottom: 0;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
	}
</style>
